<template>
  <Panel>
    <template #title>
      <span>添加账号</span>
    </template>
    <template>
      <el-form
        :model="userForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        size="small"
      >
        <!-- 账号 -->
        <el-form-item label="账号" prop="uname">
          <el-input
            type="text"
            v-model="userForm.uname"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="passwad">
          <el-input
            type="password"
            v-model="userForm.passwad"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 下拉框 -->
        <el-form-item label="用户组" prop="userGroup">
          <el-select
            v-model="userForm.userGroup"
            size="small"
            placeholder="请选择用户组"
          >
            <el-option label="普通管理员" value="普通管理员"> </el-option>
            <el-option label="超级管理员" value="超级管理员"> </el-option>
          </el-select>
        </el-form-item>
        <!-- 添加重置 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >添加</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
  </Panel>
</template>

<script>
import {
  validateUname,
  validatePasswad,
  validateGroup
} from '@/utils/validator.js'
import { addAccount } from '../../api/users.js'
export default {
  data() {
    return {
      userForm: {
        uname: '',
        passwad: '',
        userGroup: ''
      },
      rules: {
        uname: [{ validator: validateUname, trigger: 'blur' }],
        passwad: [{ validator: validatePasswad, trigger: 'blur' }],
        userGroup: [{ validator: validateGroup, trigger: 'change' }]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 验证通过,可以发请求了
          const { code, msg } = await addAccount({
            account: this.userForm.uname,
            password: this.userForm.passwad,
            userGroup: this.userForm.userGroup
          })
          if (code === 0) {
            this.$message.success(msg)
            setTimeout(() => {
              this.$router.push('/account/list')
            }, 3000)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-select,
.el-input {
  width: 200px;
}
</style>
